from django.contrib import admin
from django.contrib.admin import AdminSite
from django import forms
from django.utils.html import format_html
from .models import PetType, Pet, AdoptionApplication

# 自定义管理站点
class PetAdoptionAdminSite(AdminSite):
    site_header = '宠物领养系统管理后台'
    site_title = '宠物领养系统'
    index_title = '欢迎使用宠物领养系统管理后台'
    
    def each_context(self, request):
        context = super().each_context(request)
        # 添加自定义CSS到上下文
        context['extra_css'] = ['css/admin_custom.css']
        return context

# 创建自定义站点实例
admin_site = PetAdoptionAdminSite(name='pet_admin')

# 定义通用的ModelAdmin类
class PetTypeAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')
    search_fields = ('name',)  # 添加这一行，使搜索功能生效

class PetAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'type', 'age', 'gender', 'status', 'created_time')
    list_filter = ('type', 'status', 'gender')
    search_fields = ('name', 'description')
    
    # 添加自定义Action
    actions = ['mark_as_available']
    
    def mark_as_available(self, request, queryset):
        queryset.update(status='available')
    mark_as_available.short_description = '将选中的宠物标记为可领养'

    # 可以选择保留或删除这个方法
    def pet_image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" class="thumbnail" />', obj.image.url)
        return '无图片'
    pet_image_preview.short_description = '图片预览'

class AdoptionApplicationAdmin(admin.ModelAdmin):
    list_display = ('id', 'pet', 'applicant', 'status', 'created_time')
    list_filter = ('status',)
    search_fields = ('applicant__username', 'pet__name', 'reason')
    readonly_fields = ('applicant', 'pet')  # 禁止修改申请人和宠物
    actions = ['approve_applications', 'reject_applications']
    
    def approve_applications(self, request, queryset):
        # 批量将选中的申请标记为已通过
        for application in queryset:
            if application.status != 'approved':
                application.status = 'approved'
                application.save()
                # 同时更新对应宠物状态
                application.pet.status = 'adopted'
                application.pet.save()
    approve_applications.short_description = '批量批准选中的领养申请'
    
    def reject_applications(self, request, queryset):
        # 批量将选中的申请标记为未通过
        queryset.update(status='rejected')
    reject_applications.short_description = '批量拒绝选中的领养申请'

    def save_model(self, request, obj, form, change):
        # 保存前获取原始状态
        old_status = None
        if change:
            # 直接从数据库获取原始对象
            original_obj = AdoptionApplication.objects.get(pk=obj.pk)
            old_status = original_obj.status
        
        # 先保存申请，确保状态更新
        super().save_model(request, obj, form, change)
        
        # 再次获取对象以确保我们有最新状态
        obj.refresh_from_db()
        new_status = obj.status
        
        # 检查状态是否从其他状态变为已通过
        if old_status != 'approved' and new_status == 'approved':
            # 更新对应宠物的状态为已领养
            pet = obj.pet
            pet.status = 'adopted'
            pet.save()
        elif old_status == 'approved' and new_status != 'approved':
            # 如果从已通过改回其他状态，将宠物状态改回可领养
            pet = obj.pet
            pet.status = 'available'
            pet.save()

# 注册模型到自定义站点
admin_site.register(PetType, PetTypeAdmin)
admin_site.register(Pet, PetAdmin)
admin_site.register(AdoptionApplication, AdoptionApplicationAdmin)

# 保留默认管理站点注册
admin.site.register(PetType, PetTypeAdmin)
admin.site.register(Pet, PetAdmin)
admin.site.register(AdoptionApplication, AdoptionApplicationAdmin)